package com.example.data_save;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

/**
  *
  * @description 数据库创建删除
  * @param 
  * @return 
  * author snjgm
  * time 2022/7/25 下午3:49
  */
public class DatabaseActivity extends AppCompatActivity implements View.OnClickListener {

    private String tDataBaseName;
    private TextView tvDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);
        findViewById(R.id.btn_createData).setOnClickListener(this);
        findViewById(R.id.btn_deleteData).setOnClickListener(this);
        tvDatabase = findViewById(R.id.tv_database);
        //生成一个测试数据库的完整路径
        tDataBaseName = getFilesDir() + "/tesd.db";
    }

    @Override
    public void onClick(View view) {
        String desc = null;
        switch (view.getId()) {
            //创建数据库
            case R.id.btn_createData:
                SQLiteDatabase sqLiteDatabase = openOrCreateDatabase(tDataBaseName, Context.MODE_PRIVATE, null);
                desc = String.format("数据库%s创建%s", sqLiteDatabase.getPath(), (sqLiteDatabase != null) ? "成功" : "失败");
                tvDatabase.setText(desc);
                break;
            case R.id.btn_deleteData:
                //删除数据库
                boolean result = deleteDatabase(tDataBaseName);
                desc = String.format("数据库%s刪除%s", tDataBaseName,result?"成功":"失敗");
                tvDatabase.setText(desc);
                break;
        }
    }
}